import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedModule } from '../../shared/shared.module';

@Component({
  selector: 'app-welcome',
  standalone: true,
  templateUrl: './welcome.component.html',
  styleUrls: ['./welcome.component.scss'],
  imports: [CommonModule, SharedModule],
})
export class WelcomeComponent implements OnInit {
  messages: any[] = [];
  messageInput = '';
  private conversationId = '';

  constructor(private cdr: ChangeDetectorRef) {
  }

  ngOnInit() {
    this.checkSupport();
    this.sendMessage(true);
  }

  private addMsg(msg: any) {
    console.log('msg:', msg);
    this.messages.push(msg);
  }

  /**
   * 检查设备是否支持sse请求
   */
  private checkSupport() {
    if (!('EventSource' in window)) {
      this.addMsg({type: 'log', msg: '当前设备不支持sse请求，请联系管理员', color: 'red'});
      return;
    }
  }

  /**
   * 发送消息
   */
  sendMessage(init?: boolean) {
    console.log('sendMessage init:', init);
    if (!init && (!this.messageInput || this.messageInput.trim().length === 0)) return;
    if (!init) {
      this.addMsg({type: 'msg', msg: this.messageInput.trim()});
    }
    let messageObject = {type: 'msgAnswer', isDone: false, msg: ''};
    console.log('messageObject:', messageObject);
    this.addMsg(messageObject);
    let url = `http://39.152.133.208:33005/api/test`;
    // let url = `/api/test`;
    fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        message: init ? '您好' : this.messageInput,
        conversationId: this.conversationId || 'null',
      }),
    }).then(r => {
      console.log('fetch r', r);
      let reader = r.body?.getReader();
      this.resolveStream(reader, messageObject);
    }).catch(e => {
      console.error('请求异常，请在控制台查看报错信息:', e);
      this.addMsg({type: 'log', msg: '请求异常，请在控制台查看报错信息', color: 'red'});
    });
    this.messageInput = '';
  }

  private resolveStream(reader: ReadableStreamDefaultReader | undefined, messageObject: any) {
    reader?.read().then(({done, value}) => {
      if (done) {
        return;
      }
      let decoder = new TextDecoder('utf8');
      const chunk = decoder.decode(value, {stream: true});
      const data = chunk.replaceAll('data:', '');
      const dataArr = data.split('\n\n');
      for (let dataOne of dataArr) {
        if (!dataOne || dataOne.trim().length === 0) continue;
        try {
          let obj = JSON.parse(dataOne);
          this.receiveMessage(messageObject, obj);
        } catch (e) {
          console.error('json解析失败:', dataOne);
        }
      }
      //继续读取stream
      this.resolveStream(reader, messageObject);
    }).catch(e => {
      console.log('resolveStream报错:', e);
      this.receiveMessage(messageObject, e);
    });
  }

  private receiveMessage(messageObject: any, data: any) {
    if (!this.conversationId && !!data.conversation_id) {
      this.conversationId = data.conversation_id;
    }
    if (data.event === 'message_end') {
      messageObject.isDone = true;
    } else if (data.event === 'agent_message') {
      let answer = data.answer;
      messageObject.msg += answer;
    } else if (data.event === 'agent_thought') {
      messageObject.agent_thought = data;
    } else if (data?.status === 503) {
      console.error('服务器503异常，请联系管理员:', data);
      this.addMsg({
        type: 'log',
        msg: `服务器异常，请联系管理员:${JSON.stringify(data)}`,
        color: 'red',
      });
    } else {
      console.log('收到一条无法解析的消息，具体可以查看控制台:', data);
      this.addMsg({
        type: 'log',
        msg: `收到一条无法解析的消息，具体可以查看控制台:${JSON.stringify(data)}`,
        color: 'red',
      });
    }
  }
}
